package ProductTest;

/*
* 线程通信的应用,经典例题:生产者,消费者问题
*
* 生产者将产品交给店员,消费者从店员这里取走产品,店员每次只能持有一定数量的产品,如果产品够了,生产者就得停下等待,如果产品不够了,消费者就得等待
*
* 分析:
* 1:有两个线程,生产者线程,消费者线程
* 2:有共享数据,店员(或者产品)
* 3:如何解决线程安全问题:同步机制,有三种方法
* 4:线程的通信 wait()  notify()
* */

class Clerk{
    private int productCount = 0;

//    生产产品
    public synchronized void produceProduct(){
        if (productCount < 20) {
            productCount ++;
            System.out.println(Thread.currentThread().getName() + "开始生产产品: " + productCount);
            notify();
        }else{
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

//    消费产品
    public synchronized void consumeProduct(){
        if (productCount > 0){
            System.out.println(Thread.currentThread().getName() + "开始消费产品:" + productCount);
            productCount --;
            notify();
        }else{
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

//生产者
class Producer extends Thread{
    private Clerk clerk;

    public Producer(Clerk clert){
        this.clerk = clert;
    }

    @Override
    public void run() {
        System.out.println(getName() + "开始生产产品: ");

        while (true) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.produceProduct();
        }
    }
}

//消费者
class Consumer extends Thread{
    private Clerk clerk;

    public Consumer(Clerk clerk){
        this.clerk = clerk;
    }

    @Override
    public void run() {
        System.out.println(getName() + "开始消费产品");
        while (true){
            try {
                Thread.sleep(109);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.consumeProduct();
        }
    }
}

public class ProductTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();

        Producer p1 = new Producer(clerk);
        p1.setName("生产者一:");

        Consumer s1 = new Consumer(clerk);
        s1.setName("消费者一:");

        p1.start();
        s1.start();
    }
}

